import React, { useRef, useState } from 'react'
import style from './index.module.scss'
import { useLocation, useNavigate } from 'react-router-dom'
import { Button, Form, Input, NavBar, Toast } from 'antd-mobile'
import { LoginForm, Rules } from '@/types/data'
import { getSMSAction, loginAction } from '@/store/reducers/login'
import { useAppDispatch } from '@/store/hook'
import { InputRef } from 'antd-mobile/es/components/input'
import { useEffect } from 'react'

export default function Login () {
  // redux-toolkit
  const dispatch = useAppDispatch()

  // 路由跳转
  const Navigate = useNavigate()
  const { state } = useLocation() as {
    state: { redirect?: string } | undefined
  }
  console.log('state!.redirect',state?.redirect)

  // form实例
  const [form] = Form.useForm<LoginForm>()

  // 手机号input框ref
  const inputRef = useRef<InputRef>(null)

  // 手机校验规则
  const mobileRules: Rules = [
    { required: true, message: '请输入手机号' },
    {
      pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
      message: '手机号格式有误'
    }
  ]

  // 验证码校验规则
  const codeRules: Rules = [
    { required: true, message: '请输入验证码' },
    { pattern: /^\d{6}$/, message: '验证码6个数字' }
  ]

  // 表单登陆
  const onFinish = async (values: LoginForm) => {
    await dispatch(loginAction(values))
    Toast.show({
      icon: 'success',
      content: '登陆成功',
      afterClose () {
        Navigate( state?.redirect ? state.redirect :`/home`, {
          replace: true
        })
      }
    })
  }

  // 发送验证码
  const VerificationCode = async () => {
    try {
      const res = await form.validateFields(['mobile'])
      await dispatch(getSMSAction(res.mobile))
      Toast.show('已发送短信😜')
      setCountdown(60)
    } catch (error) {
      inputRef.current?.focus()
    }
  }

  // 倒计时
  const [countdown, setCountdown] = useState(0)
  useEffect(() => {
    let timer: NodeJS.Timeout
    if (countdown > 0) {
      timer = setTimeout(() => {
        setCountdown(countdown => countdown - 1)
      }, 1000)
    }
    return () => {
      clearTimeout(timer)
    }
  }, [countdown])

  return (
    <div className={style.root}>
      <NavBar onBack={() => Navigate(-1)}></NavBar>
      <div className='login-form'>
        <h2 className='title'>短信登陆</h2>
        <Form
          form={form}
          onFinish={onFinish}
          initialValues={{
            mobile: '13911111111',
            code: '246810'
          }}
        >
          <Form.Item className='login-item' name='mobile' rules={mobileRules}>
            <Input
              ref={inputRef}
              autoComplete='off'
              placeholder='请输入手机号'
            />
          </Form.Item>
          <Form.Item
            className='login-item'
            name='code'
            rules={codeRules}
            extra={
              countdown === 0 ? (
                <span className='code-extra' onClick={VerificationCode}>
                  发送验证码
                </span>
              ) : (
                <span className='code-extra'>还剩{countdown}秒</span>
              )
            }
          >
            <Input autoComplete='off' placeholder='请输入验证码' />
          </Form.Item>

          <Form.Item>
            <Button
              type='submit'
              color='primary'
              block
              className='login-submit'
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
